<template>
  <div>
    <el-row class="container">
      <!-- 头部 -->
      <el-col :span="24" class="header">

        <!-- ... 头部的其他内容 ... -->
        <el-col :span="10" class="logo" :class="collapsed?'logo-collapse-width':'logo-width'">
          {{ collapsed ? '' : sysName }}
        </el-col>

        <el-col :span="16" class="notice_box">
          <!-- 公告图片 -->
          <img src="../assets/notice.gif" alt="GIF" class="gif-image">
          <div id="center-bottom-board">
            <div class="wrapper" ref="wrapper">
              <div class="marquee" ref="marquee">
                <div class="marquee-content" ref="marqueeContent">
                  <i class="el-icon-bell"></i> {{ items[0] }}
                </div>
              </div>
            </div>
          </div>
        </el-col>


        <el-col :span="4" class="userinfo">
          <el-dropdown trigger="hover">
            <span class="el-dropdown-link userinfo-inner">
             <img :src="sysUserAvatar || defaultAvatar" :class="{ shake: isNewMessage }"/>
              {{ sysUserName }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="showMessages">
                我的消息
                <el-badge v-if="unreadMessages.length > 0" :value="unreadMessages.length">
                </el-badge>
              </el-dropdown-item>
              <el-dropdown-item @click.native="setup">设置</el-dropdown-item>
              <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-col>


      <!-- 主体内容 -->
      <el-col :span="24" class="main">

        <aside :class="collapsed?'menu-collapsed':'menu-expanded'">
          <!--导航菜单-->
          <el-menu :default-active="$route.path" class="el-menu-vertical-demo" @open="handleopen" @close="handleclose"
                   @select="handleselect"
                   unique-opened router v-show="!collapsed">
            <template v-for="(item,index) in $router.options.routes" v-if="!item.hidden">
              <el-submenu :index="index+''" v-if="!item.leaf">
                <template slot="title"><i :class="item.iconCls"></i>{{ item.name }}</template>
                <el-menu-item v-for="child in item.children" :index="child.path" :key="child.path" v-if="!child.hidden">
                  {{ child.name }}
                </el-menu-item>
              </el-submenu>
              <el-menu-item v-if="item.leaf&&item.children.length>0" :index="item.children[0].path"><i
                  :class="item.iconCls"></i>{{ item.children[0].name }}
              </el-menu-item>
            </template>
          </el-menu>
          <!--导航菜单-折叠后-->
          <ul class="el-menu el-menu-vertical-demo collapsed" v-show="collapsed" ref="menuCollapsed">
            <li v-for="(item,index) in $router.options.routes" v-if="!item.hidden" class="el-submenu item">
              <template v-if="!item.leaf">
                <div class="el-submenu__title" style="padding-left: 20px;" @mouseover="showMenu(index,true)"
                     @mouseout="showMenu(index,false)"><i :class="item.iconCls"></i></div>
                <ul class="el-menu submenu" :class="'submenu-hook-'+index" @mouseover="showMenu(index,true)"
                    @mouseout="showMenu(index,false)">
                  <li v-for="child in item.children" v-if="!child.hidden" :key="child.path" class="el-menu-item"
                      style="padding-left: 40px;" :class="$route.path==child.path?'is-active':''"
                      @click="$router.push(child.path)">{{ child.name }}
                  </li>
                </ul>
              </template>
              <template v-else>
                <ul>
                  <li class="el-submenu">
                    <div class="el-submenu__title el-menu-item"
                         style="padding-left: 20px;height: 56px;line-height: 56px;padding: 0 20px;"
                         :class="$route.path==item.children[0].path?'is-active':''"
                         @click="$router.push(item.children[0].path)"><i :class="item.iconCls"></i></div>
                  </li>
                </ul>
              </template>
            </li>
          </ul>
        </aside>
        <!--        历史任务栏-->
        <div class="history-taskbar" ref="historyTaskbar">
          <transition-group name="fade" tag="div" class="history-taskbar-container">
            <el-tag
                v-for="(item, index) in filteredHistoryTaskbar"
                :key="item.path"
                :closable="true"
                @close="removeFromHistory(index)"
                :type="$route.path === item.path ? 'primary' : 'info'"
                :effect="$route.path === item.path ? 'dark' : ''"
                class="history-item"
                @click="navigateToPage(item.path)"
                :style="$route.path === item.path ? 'padding-left: 25px; position: relative;' : 'padding-left: 10px; position: relative;'"
            >
              <!-- 当前路径匹配时显示小圆点 -->
              <span v-if="$route.path === item.path" class="dot"></span>
              {{ item.name }}
            </el-tag>
          </transition-group>
        </div>
        <div class="right_body">
          <section class="content-container">
            <div class="grid-content bg-purple-light">
              <!-- 面包屑导航 -->
              <el-col :span="24" class="breadcrumb-container">
                <strong class="title">{{ $route.name }}</strong>
                <el-breadcrumb separator="/" class="breadcrumb-inner">
                  <el-breadcrumb-item v-for="item in $route.matched" :key="item.path">
                    {{ item.name }}
                  </el-breadcrumb-item>
                </el-breadcrumb>
              </el-col>

              <!-- 页面主体内容 -->
              <el-col :span="24" class="content-wrapper">
                <transition name="fade" mode="out-in">

                  <router-view></router-view>
                </transition>
              </el-col>
            </div>
          </section>
        </div>

      </el-col>

    </el-row>

  </div>
</template>

<script>
import {Notification} from 'element-ui';

export default {
  watch: {
    // 监听路由的变化，在路由变化时调用 updateHistoryTaskbar 方法
    $route(to, from) {
      this.updateHistoryTaskbar();
    },
    historyTaskbar: {
      handler(newHistoryTaskbar) {
        // Check if the history taskbar is empty and redirect to the homepage if it is
        if (newHistoryTaskbar.length === 0) {
          this.$router.push('/echarts');
        }
      },
      deep: true, // Watch changes deeply in the array
    },
  },

  data() {
    return {
      //未读消息
      unreadMessages: [],
      //是否抖动
      isNewMessage: false,
      //抖动时间
      shakeInterval: null,
      //
      //默认头像
      defaultAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      sysName: '空气虫',
      collapsed: false,
      sysUserName: '',
      sysUserAvatar: '',
      historyTaskbar: [], // 新增历史任务栏数组
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      items: [], // 滚动的内容
      currentPosition: 0, // 当前滚动位置
      totalWidth: 0, // 滚动内容的总宽度
      animationId: null,// requestAnimationFrame 的 ID
      scrollSpeed: 1, // 滚动速度，可以调整
      //sse连接对象
      eventSource: null,
    }
  },
  computed: {
    filteredHistoryTaskbar() {
      // 指定要从历史导航栏中排除的路由
      const excludedRoutes = ['/CustomeraAddorder', '/OrderToAddCustomer', '/MyToAddCustomer', '/examine'];

      // 过滤掉被排除的路由
      return this.historyTaskbar.filter((item) => !excludedRoutes.includes(item.path));
    },
    contentStyle() {
      return {
        'animation-duration': this.animationDuration,
      };
    },
  },

  beforeDestroy() {
    // 在组件销毁前关闭SSE连接
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  methods: {
    //sse连接
    connectToServer() {
      if (this.eventSource) {
        this.eventSource.close();
      }
      //创建新的实例对象
      const logininfo = JSON.parse(localStorage.getItem("logininfo"));
      const userId = logininfo.id;
      this.eventSource = new EventSource(`https://www.kongqichong.com:8080/sse/store/${userId}`);
      this.eventSource.onopen = () => {
        console.log('SSE连接成功');
      };
      this.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        // 根据消息类型处理不同的消息
        if (data.type === 'announcement') {
          this.items = [];
          this.items.push(data.content);
          this.$nextTick(() => {
            this.move();
          });
        } else if (data.type === 'order') {
          this.unreadMessages.push(data.content);
          // 新消息头像抖动
          // 如果当前没有抖动，则开始抖动
          if (!this.isNewMessage) {
            this.startShaking();
          }
          Notification({
            title: '新消息',
            message: data.content,
            type: 'info',
            duration: 3000,
            offset: 50,
          });
        }
      };

      this.eventSource.onerror = (error) => {
        console.error('错误信息:', error);
        this.eventSource.close();
        this.reconnectToServer();
      };
    },
    reconnectToServer() {
      setTimeout(() => {
        console.log('尝试重新连接SSE...');
        this.connectToServer();
      }, 5000); // 5秒后尝试重新连接
    },
//展示未读消息
    showMessages() {
      // 弹出每条未读消息的通知框
      this.unreadMessages.forEach((message, index) => {
        this.showNotification(message, index);
      });
      // 清空未读消息数组
      this.unreadMessages = [];
      // 停止抖动
      this.stopShaking();
    },

    showNotification(messageContent, index) {
      this.$notify({
        title: '新消息',
        message: messageContent,
        type: 'success',
        duration: 0,
        offset: 60 + index * 100
      });
    },
    // 开始头像抖动
    startShaking() {
      this.isNewMessage = true;
      this.shakeInterval = setInterval(() => {
        this.isNewMessage = !this.isNewMessage;
      }, 3000); // 每3秒切换一次抖动状态
    },
    // 停止头像抖动
    stopShaking() {
      this.isNewMessage = false;
      clearInterval(this.shakeInterval);
    },
//公告滚动
    move() {
      // 确保 $refs 已经更新
      let wrapper = this.$refs.wrapper;
      let wrapperWidth = wrapper.getBoundingClientRect().width;
      let marquee = this.$refs.marquee;
      let marqueeContent = this.$refs.marqueeContent;
      let contentWidth = marqueeContent.getBoundingClientRect().width;
      let distance = wrapperWidth;
      let moveSpeed = 1;
      setInterval(() => {
        if (marquee && marqueeContent && wrapper) {
          if (marquee.getBoundingClientRect().x + contentWidth < wrapper.getBoundingClientRect().x) {
            distance = wrapperWidth;
          }
          distance -= moveSpeed;
          marquee.style.transform = 'translateX(' + distance + 'px)';
        }
      }, 20);
    },
    updateHistoryTaskbar() {
      const routeInfo = {
        name: this.$route.name,
        path: this.$route.path,
        timestamp: Date.now(),
      };
      const existingIndex = this.historyTaskbar.findIndex(
          (item) => item.path === routeInfo.path
      );
      if (existingIndex === -1) {
        // 如果页面不存在于历史任务栏中，将其添加到最右边
        this.historyTaskbar.push(routeInfo);
        // 调整历史任务栏项大小
        // this.adjustHistoryItemSize();
      }
    },
    adjustHistoryItemSize() {
      const historyTaskbarContainer = this.$refs.historyTaskbar;
      const historyItems = Array.from(historyTaskbarContainer.querySelectorAll('.history-item'));
      // 为每个项设置固定宽度
      const fixedWidth = 70; // 设置所需的固定宽度
      historyItems.forEach(item => {
        item.style.minWidth = `${fixedWidth}px`;
      });
    },
    removeFromHistory(index) {
      // 从历史任务栏中移除指定索引的项
      const removedItem = this.historyTaskbar.splice(index, 1)[0];
      // 检查历史任务栏中是否仍然有项
      if (this.historyTaskbar.length > 0) {
        // 获取历史任务栏中上一个项的路径
        const lastPath = this.historyTaskbar[this.historyTaskbar.length - 1].path;
        // 如果删除的是当前路径，导航到上一个项的路径
        if (this.$route.path === removedItem.path) {
          this.$router.push({path: lastPath, query: {_refresh: Date.now()}});
        }
      } else {
        // 如果历史任务栏为空，导航到默认页面（例如，首页）
        this.$router.push('/echarts');
      }
    },

    navigateToPage(path) {
      // 点击历史任务时跳转到指定页面
      this.$router.push({path: path, query: {_refresh: Date.now()}});
    },
    handleopen() {
      //console.log('handleopen');
    },
    handleclose() {
      //console.log('handleclose');
    },
    handleselect: function (a, b) {
    },
    setup: function () {
      this.$router.push('/AccountMag');
    },
    //退出登录
    logout: function () {
      this.$confirm('确认退出吗?', '提示', {
        //type: 'warning'
      }).then(() => { //点击确认
        //前端的处理
        localStorage.removeItem('token');
        localStorage.removeItem('logininfo');
        localStorage.removeItem('permissions');
        localStorage.removeItem('menus');
        //后端需要处理：redis中的登录信息删除 - token - 不做 - 后面要改
        //跳转到登录页面
        this.$router.push('/login');
      }).catch(() => { //点击取消
      });
    },

    //折叠导航栏
    collapse: function () {
      this.collapsed = !this.collapsed;
    },
    showMenu(i, status) {
      this.$refs.menuCollapsed.getElementsByClassName('submenu-hook-' + i)[0].style.display = status ? 'block' : 'none';
    },

  },

  mounted() {
    this.connectToServer();
    this.$nextTick(() => {
      this.move();
    });
    var logininfo = localStorage.getItem('logininfo');
    if (logininfo) {
      let logininfoObj = JSON.parse(logininfo);
      this.sysUserName = logininfoObj.username;
      this.sysUserAvatar = logininfoObj.avatar;
      // this.sysUserAvatar = loginInfoObj.avatar || '';//显示管理员头像，表中没有设计
    }
    // 在页面加载时执行一次，确保初始时也调整历史任务栏项大小
    // this.adjustHistoryItemSize();
    // 如果没有历史任务时，跳转到首页
    if (this.historyTaskbar.length === 0 && !this.$route.path) {
      this.$router.push('/echarts');
    }

  },


}

</script>


<style scoped lang="scss">
@import '~scss_vars';

.container {
  position: absolute;
  top: 0px;
  bottom: 0px;
  width: 100%;
  overflow: hidden;

  .header {
    height: 60px;
    line-height: 60px;
    background: $color-primary;
    color: #fff;

    .notice_box {
      height: 60px;
      display: flex;
      flex-direction: row;
    }

    .userinfo {
      text-align: right;
      padding-right: 35px;
      float: right;

      .userinfo-inner {
        cursor: pointer;
        color: #fff;

        img {
          width: 50px;
          height: 50px;
          border-radius: 25px;
          margin: 10px 0px 10px 10px;
          float: right;
        }
      }
    }

    .logo {
      //width:230px;
      height: 60px;
      font-size: 22px;
      padding-left: 20px;
      padding-right: 20px;
      border-color: rgba(238, 241, 146, 0.3);
      border-right-width: 1px;
      border-right-style: solid;

      img {
        width: 40px;
        float: left;
        margin: 10px 10px 10px 18px;
      }

      .txt {
        color: #fff;
      }
    }

    .logo-width {
      width: 230px;
    }

    .logo-collapse-width {
      width: 60px
    }

    .tools {
      padding: 0px 23px;
      width: 14px;
      height: 60px;
      line-height: 60px;
      cursor: pointer;
    }
  }

  .history-taskbar {
    top: 60px;
    width: calc(100% - 230px);
    left: 230px;
    bottom: 8px;
    display: flex;
    align-items: center;
    padding: 5px;
    height: 45px;
    position: fixed;
    background-color: #fff;
    border: none; /* 移除所有边框 */
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); /* 添加轻微阴影效果 */
    overflow-x: auto; /* 当内容超出容器宽度时，允许横向滚动 */
    white-space: nowrap; /* 禁止内容自动换行，使所有内容在同一行显示 */
  }

  /* 历史任务栏的内层容器 */
  .history-item-container {
    min-width: 70px;
    display: flex;
    align-items: center;
    margin-right: 10px;
    transition: width 0.3s; /* 添加过渡效果 */
    overflow-x: auto; /* 允许横向溢出内容时滚动 */
    scrollbar-width: thin; /* 统一滚动条宽度为较细的尺寸 */
    padding-bottom: 8px; /* 添加底部内边距 */
  }

  /* 滚动条 hover 时显示 */
  .history-taskbar-container:hover::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.5); /* 滚动条 hover 时的颜色 */
  }

  .history-item {
    padding-left: 5px; /* 为圆点留出更多空间 */
    // position: relative; /* 设置为相对定位，以便子元素使用绝对定位 */
    cursor: pointer;
    //color: #303133;
    margin-right: 8px; /* 调整历史任务栏项和删除按钮之间的距离 */
  }

  .history-item .el-tag {
    margin: 8px; /* 设置所有方向的外边距为5px，使标签之间有一定间距 */
  }


  .remove-icon {
    cursor: pointer;
    color: #cbcbcb; /* 删除按钮颜色 */
    font-size: 16px;
  }

  .remove-icon:hover {
    color: #9b9090;
  }

  .current-task {
    background-color: #fff; /* 当前任务项的背景颜色 */
    min-width: 70px;
    // 添加其他样式，如边框、阴影等
  }

  .main {
    display: flex;
    // background: #324057;
    position: absolute;
    top: 60px;
    bottom: 0px;
    overflow: hidden;
    height: 100%;

    .right_body {
      width: calc(100% - 230px);
      margin-top: 25px;
      overflow-y: auto;
    }

    aside {
      flex: 0 0 230px;
      width: 230px;
      // position: absolute;
      // top: 0px;
      // bottom: 0px;
      .el-menu {
        height: 100%;
      }

      .collapsed {
        width: 60px;

        .item {
          position: relative;
        }

        .submenu {
          position: absolute;
          top: 0px;
          left: 60px;
          z-index: 99999;
          height: auto;
          display: none;
        }

      }
    }

    .menu-collapsed {
      flex: 0 0 60px;
      width: 60px;
      overflow-y: auto; /* 启用垂直滚动 */
    }

    .menu-expanded {
      flex: 0 0 230px;
      width: 230px;
      overflow-y: auto; /* 启用垂直滚动 */
    }

    .content-container {
      // background: #f1f2f7;
      flex: 1;
      // position: absolute;
      // right: 0px;
      // top: 0px;
      // bottom: 0px;
      // left: 230px;

      padding: 10px;

      .breadcrumb-container {
        //margin-bottom: 15px;
        .title {
          width: 200px;
          float: left;
          color: #475669;
        }

        .breadcrumb-inner {
          float: right;
        }
      }

      .content-wrapper {
        background-color: #fff;
        box-sizing: border-box;
      }
    }
  }
}

.scroll-container-wrapper {
  overflow: hidden;
}

.scroll-container {
  align-items: center;
  white-space: nowrap;

}

.scroll-content {
  display: flex;
  padding: 0;
  margin: 0;
  list-style: none;
}

.scroll-item {
  display: inline-block;
  margin-right: 20px;
}

//@keyframes scrollAnimation {
//  0% {
//    transform: translateX(0);
//  }
//
//  100% {
//    transform: translateX(calc(-100% - 20px)); /* 加上额外的距离，以避免粘滞 */
//  }
//}
.gif-image {
  width: 80px; /* 设置图片宽度 */
  display: block; /* 确保图片显示为块级元素 */
}

.wrapper {
  overflow: hidden; /* 隐藏超出的内容 */
  white-space: nowrap; /* 防止换行 */
}

.marquee {
  display: inline-block; /* 内容水平排列 */
  animation: marquee 25S linear infinite;
}

@keyframes marquee {
  from {
    transform: translateX(100%); /* 初始位置 */
  }
  to {
    transform: translateX(-100%); /* 滚动至最左边 */
  }
}

.marquee-content {
  display: inline-block;
}

/* 历史任务栏移除时过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

</style>
<style scoped>
@keyframes shake {
  0%, 100% {
    transform: translateX(0);
  }
  20%, 60% {
    transform: translateX(-10px);
  }
  40%, 80% {
    transform: translateX(10px);
  }
}

.shake {
  animation: shake 0.5s;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.dot {
  position: absolute;
  left: 8px; /* 调整圆点位置 */
  top: 50%; /* 居中 */
  transform: translateY(-50%);
  width: 10px;
  height: 10px;

  background-color: #fff;
  border-radius: 50%; /* 圆形 */
}</style>